package com.service;

import com.dto.AuthRequest;
import com.dto.AuthResponse;
import com.entity.SystemUser;
import com.exception.BusinessException;
import com.repository.SystemUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@Transactional
public class SystemUserService {
    
    @Autowired
    private SystemUserRepository userRepository;
    
    public Optional<SystemUser> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public Page<SystemUser> findAll(int page, int size) {
        return userRepository.findAll(PageRequest.of(page, size));
    }
    
    public SystemUser save(SystemUser user) {
        Optional<SystemUser> userOptional = userRepository.findByUsername(user.getUsername());
        if (userOptional.isPresent()) {
            SystemUser user0 = userOptional.get();
            user0.setPassword(user.getPassword());
            if (!"admin".equals(user.getUsername())) {
                user0.setPermission(user.getPermission());
            }

            return userRepository.save(user0);
        }
        return userRepository.save(user);
    }

    public void delete(Integer id) {
        userRepository.deleteById( id);
    }

    public AuthResponse login(AuthRequest user) {
        SystemUser user0 = userRepository.findByUsername(user.getUsername()).orElse( null);
        if (user0 == null) {
            if ("admin".equals(user.getUsername())) {
                userRepository.save(new SystemUser(user.getUsername(), user.getPassword(), "2,3,4,5,6,7,8,9,10,11,12,13"));
                return AuthResponse.builder().username(user.getUsername()).permission("2,3,4,5,6,7,8,9,10,11,12,13").build();
            }
            throw new BusinessException("用户不存在");
        }
        if (!user0.getPassword().equals(user.getPassword())) {
            throw new BusinessException("用户名或者密码错误");
        }
        return AuthResponse.builder().username(user0.getUsername()).permission(user0.getPermission()).build();
    }
}